package hk.linkcredit.walletservice.wallet.service.strategy;

import hk.linkcredit.walletservice.constant.WalletConstants;
import hk.linkcredit.walletservice.wallet.domain.entity.WalletOrder;
import hk.linkcredit.walletservice.wallet.domain.vo.WalletAccountMsg;
import hk.linkcredit.walletservice.wallet.domain.vo.WalletOrderReq;
import hk.linkcredit.walletservice.wallet.service.AsyncService;
import hk.linkcredit.walletservice.wallet.service.WalletOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @Author: Jamnsin
 * @Date: 2022/6/12 16:26
 */
@Slf4j
@Component(WalletConstants.WALLET_ORDER_STATUS_3)
public class OrderSuccessStrategy extends OrderStatusService implements OrderStatusStrategy {

    @Autowired
    WalletOrderService walletOrderService;

    @Autowired
    AsyncService asyncService;

    @Override
    public void dealWalletOrder(WalletOrderReq walletOrderReq) {
        log.info("开始处理钱包订单状态 >>> orderStatus = {}, walletOrderReq = {}", WalletConstants.WALLET_ORDER_STATUS_SUCCESS, walletOrderReq);

        if (!isRepayOrder(walletOrderReq.getOrderType())) {
            WalletOrder walletOrder = this.getWalletOrder(walletOrderReq.getCustNo(), walletOrderReq.getOrderSerialNo());
            walletOrderService.doWalletOrder(walletOrderReq, walletOrder);

            WalletAccountMsg walletAccountMsg = WalletAccountMsg.builder().custNo(walletOrder.getCustNo()).walletType(walletOrder.getWalletType()).changeType(WalletConstants.WALLET_FLOW_EXPEND).fundsType(walletOrder.getOrderType()).changeAmount(walletOrder.getAmount().add(walletOrder.getServiceFee())).changeTime(new Date()).build();
            asyncService.sendWalletAccountAmountMessage(walletAccountMsg);
            return;
        }

        List<WalletOrder> walletOrders = this.getWalletOrders(walletOrderReq.getCustNo(), walletOrderReq.getOrderSerialNo());
        walletOrders.forEach(walletOrder -> {
            walletOrderService.doWalletOrder(walletOrderReq, walletOrder);

            WalletAccountMsg walletAccountMsg = WalletAccountMsg.builder().custNo(walletOrder.getCustNo()).walletType(walletOrder.getWalletType()).changeType(WalletConstants.WALLET_FLOW_EXPEND).fundsType(walletOrder.getOrderType()).changeAmount(walletOrder.getAmount().add(walletOrder.getServiceFee())).changeTime(new Date()).build();
            asyncService.sendWalletAccountAmountMessage(walletAccountMsg);
        });
    }
}
